<template>
	<div>
		登录
	</div>
</template>
<script>
  import {getUserBackUrl,setUserBackUrl, getInvid, getToken,setToken} from '@/libs/util'
  import {getGzhAppid, wxLogin} from '@/api/wx'

  export default {
    name: 'login',
    data() {
      return {}
    },
    created() {
      if (getToken()) {
        this.$router.go(-1);
      }
      let code = this.GLOBAL.getQueryString('code');
      if (code === undefined || code === null) {
        this.getCode();
      } else {
        this.login(code);
      }
    },
    methods: {
      getCode() {
        getGzhAppid().then(rep => {
          var appid = rep.data.data;
          var weburl = window.location.host;
          weburl = "http://" + weburl;
          weburl += "/login";
          weburl = encodeURIComponent(weburl);
          var url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + appid + '&redirect_uri=' + weburl + '&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';
          window.location.href = url;
        });
      },
      login(code) {
        let vm = this;
        let params = {code: code};
        wxLogin(params).then(rep => {
          setToken( rep.data.data.token)
          let url = getUserBackUrl();
          let host = vm.GLOBAL.getHostWithProtocal();
          setUserBackUrl('');
          if (url && url.indexOf("/login") === -1&&url!=='/') {
            window.location.href = host+url;
            vm.$router.push({
              path: url
            })
          } else {
            vm.$router.push({
              path: 'home'
            })
          }

        });
      }
    }
  }
</script>
